import { createApp } from 'vue'
import App from './App.vue'
import router from './router'
import store from './store'
//1.引入ElementPlus组件库
import ElementPlus, {ElMessage} from 'element-plus'
import 'element-plus/dist/index.css'
//3.引入ElementPlus图标库
import * as ElementPlusIconsVue from '@element-plus/icons-vue'
//5.1修改elementPlus默认中文
import zhCn from 'element-plus/dist/locale/zh-cn.mjs'
import axios from "axios";

//9.1配置根路径
const BASE_URL = 'http://localhost:8080';
//window是全局对象,给它设置属性,此属性可以在任意script标签中使用!
window.BASE_URL = BASE_URL;

const app = createApp(App)
//9.2 给app也就是vue实例也设置根路径,这样可以在任意template标签中使用!
app.config.globalProperties.BASE_URL = BASE_URL;

//4.遍历ElementPlusIconsVue图标库，并将所有图标组件注册到vue实例app中
for (const [key, component] of Object.entries(ElementPlusIconsVue)) {
    app.component(key, component)
}
//2. .use(ElementPlus)给当前vue实例应用ElementPlus组件库
//5.2 app.use(ElementPlus,{ locale: zhCn })将El本地化为中文
app.use(ElementPlus,{ locale: zhCn }).use(store).use(router).mount('#app')


//6.解决ResizeObserver Error
const debounce = (fn, delay) => {
    let timer = null;
    return function () {
        let context = this;
        let args = arguments;
        clearTimeout(timer);
        timer = setTimeout(function () {
            fn.apply(context, args);
        }, delay);
    }
}
const _ResizeObserver = window.ResizeObserver;
window.ResizeObserver = class ResizeObserver extends _ResizeObserver {
    constructor(callback) {
        callback = debounce(callback, 16);
        super(callback);
    }
}
//7.定义获取当前登录用户的全局方法
window.getUser = ()=>{
    //如果没有获取到user数据,将undefined转为null值
    //如果获取到了user数据,需要将存入时的JSON字符串转回JS对象,方便后续使用
    return localStorage.user ? JSON.parse(localStorage.user) : null;
}
//8.设置路由守卫: 每次使用路由跳转前触发,确保用户在访问其他页面时,已经登录
router.beforeEach((to, from, next) =>{
    //to即将访问的目标 from即将离开的路由 next路由导航守卫的动作函数
    //从localStorage中获取user数据
    let user = localStorage.user;
    //如果目标路径不是登录页或首页,且用户数据为空
    if(to.path !== '/login' && !user && to.path !== '/'){
        //就重定向到登录页,且提示"请先登录!"
        //query: { redirect: to.fullPath}
        //是将用户尝试访问的完整路径作为查询参数传递给登录页面http://localhost:9090/login?redirect=/user
        next({ path: '/login',query:{redirect:to.fullPath}},ElMessage.error('请先登录'))
    }else{
        next()//如果目标路径是登录页或首页,或用户已登录，则允许路由跳转
    }
})

//10.创建根据字典code加载其对应的所有字典项的全局方法
window.loadDictOptions = (object,dictCode) =>{
    //向后端请求查所有的字典项
    axios.get(BASE_URL+'/v1/dictOption/select/'+dictCode).then((response)=>{
        if(response.data.code === 2000){
            object.value = response.data.data;
        }else{
            ElMessage.error(response.data.msg);
        }
    })
}
